import React from 'react'
import { connect } from 'react-redux'
import { validForm as validFormDuck } from 'ducks'
import { Form } from 'semantic-ui-react'
import PropTypes from 'prop-types'

class ValidForm extends React.Component {
  componentDidMount() {
    const { actionInitForm, children } = this.props
    const initValues = {}
    React.Children.forEach(children, (element) => {
      const {
        name,
        valid,
        defaultValue,
      } = element.props
      if (valid) {
        initValues[name] = {
          value: defaultValue,
          state: 'init',
        }
      }
    })
    actionInitForm(initValues)
  }

  componentWillUnmount() {
    const { actionResetForm } = this.props
    actionResetForm()
  }

  render() {
    const {
      error,
      loading,
      size,
      success,
      children,
      isFormInit,
    } = this.props
    return (
      <Form
        error={error}
        loading={loading}
        size={size}
        success={success}
      >
        {
          isFormInit && children
        }
      </Form>
    )
  }
}

ValidForm.propTypes = {
  actionInitForm: PropTypes.func.isRequired,
  actionResetForm: PropTypes.func.isRequired,
  children: PropTypes.node.isRequired,
  error: PropTypes.bool.isRequired,
  loading: PropTypes.bool.isRequired,
  size: PropTypes.string.isRequired,
  success: PropTypes.bool.isRequired,
  isFormInit: PropTypes.bool.isRequired,
}

const mapStateToProps = state => ({
  formValues: validFormDuck.selectors.formValues(state),
  isFormInit: validFormDuck.selectors.isFormInit(state),
})

const mapDispatchToProps = {
  actionInitForm: validFormDuck.creators.actionInitForm,
  actionResetForm: validFormDuck.creators.actionResetForm,
  actionFieldChange: validFormDuck.creators.actionFieldChange,
}

export default connect(mapStateToProps, mapDispatchToProps)(ValidForm)
